# -*- coding: utf-8 -*-

from openerp.osv import fields, osv
from openerp.addons import warning
import openerp.netsvc as netsvc
class purchase_order(osv.osv):
    _inherit = "purchase.order"
    _order = 'write_date desc'
    _columns = {
        'has_pur_invoice': fields.boolean("Has Purchase Invoice?"),
        'is_print_signature': fields.boolean("Print Signature?"),
        'pur_pick_method': fields.many2one('option.list','交提货方式', ondelete='restrict',
                                           domain=[('option_name','=','pur_pick_method')]),
        'trans_fee_method': fields.many2one('option.list','运输方式及到达站和费用负担', ondelete='restrict',
                                           domain=[('option_name','=','trans_fee_method')]),
        'box_marks': fields.char("外箱唛头要求",size=200),
        'pack_memo': fields.char("装箱规格要求",size=200),
        'pack_standard': fields.char("包装标准，包装物的供应与回收",size=200),
        'quanlity_desc': fields.text("质量要求、技术标准，供方对质量负责的条件和期限"),
        'create_date': fields.datetime('Creation Date', readonly=True, select=True, help="Date on which sales order is created."),
    }

    _defaults = {
        'quanlity_desc': '供方交货货物品质必须达到和满足需方外商客户确认样的 品质要求;\n\
货物出运前需方或需方外商客户派员检验货物，其抽查质量所出具的验货报告只作为是否符合出运条件的前提判断，不能作为对本批货物整体质量是否合 格的客观判定依据，最终以货物到达需方外方客商仓库后的检验结果为准；质量异议期限为货物达到目的港后90天，凭第三方公共检验机构有效证据，如供方在接 到需方书面异议后，应3在个工作日内负责处理，否则即视为已默认需方提出的异议和处理意见。',
        'is_print_signature': True,
        'pack_memo': '单箱毛重不得超过20KGS。',
        'pack_standard': '外箱为普通出口五层瓦楞纸箱。供方负责采购包装材料并完成包装。费用由供方承担。'
    }
    #依据partner的'采购开票'字段,自动设置采购单的'采购开票'字段
    def onchange_partner_id(self, cr, uid, ids, partner_id):
        partner = self.pool.get('res.partner')
        if not partner_id:
            return {'value': {
                'fiscal_position': False,
                'payment_term_id': False,
                }}
        supplier_address = partner.address_get(cr, uid, [partner_id], ['default'])
        supplier = partner.browse(cr, uid, partner_id)
        return {'value': {
            'pricelist_id': supplier.property_product_pricelist_purchase.id,
            'fiscal_position': supplier.property_account_position and supplier.property_account_position.id or False,
            'payment_term_id': supplier.property_supplier_payment_term.id or False,
            'has_pur_invoice': supplier.has_pur_invoice or False,
            }}
        
    def print_quotation(self, cr, uid, ids, context=None):
#        self.check_wkf(cr,uid,ids)
        rpt_info = super(purchase_order,self).print_quotation(cr, uid, ids, context)
        rpt_info.update({'report_name':'purchase.order.lijin'})
        return rpt_info
 
        
class purchase_order_line(osv.osv):    
    _inherit = "purchase.order.line"
    _columns = {
                'ret_tax_rate':fields.related('product_id', 'ret_tax_rate', type="integer", string="Export Return Tax Rate(%)", readonly=True),
                'name': fields.text('Description', required=True, translate=True),}      
    
class purchase_order_line_lijin(warning.warning.purchase_order_line):
    #If we use the common method as extending osv.osv and use the '_inherit' do to inherit, 
    #then warning.warning.purchase_order_line.onchange_product_id will be called before our class, and it call call our method and has_pur_invoice can not be given  
    #If use python class to extend then our method will be called firstly, then we can get parameter has_pur_invoice

    def onchange_product_id(self, cr, uid, ids, pricelist_id, product_id, qty, uom_id,
                partner_id, date_order=False, fiscal_position_id=False, date_planned=False,
                name=False, price_unit=False, has_pur_invoice=False, context=None): 
        if context is None:
                    context = {}    
        product_vals = super(purchase_order_line_lijin,self).onchange_product_id(
                cr, uid, ids, pricelist_id, product_id, qty, uom_id,
                partner_id, date_order, fiscal_position_id, date_planned,
                name, price_unit, context)
        if not product_id:
            return product_vals
        product_product = self.pool.get('product.product')
        res_partner = self.pool.get('res.partner')
        context_partner = context.copy()
        partner = None
        if partner_id:
            lang = res_partner.browse(cr, uid, partner_id).lang
            context_partner.update( {'lang': lang, 'partner_id': partner_id} )
            partner = res_partner.browse(cr,uid,partner_id,context_partner)
        product = product_product.browse(cr, uid, product_id, context_partner)
        #update the 'name' to product description                
        product_vals['value'].update({'name': product.description})   
        #两种情况不进行价格计算:1.采购开票且采购价格含税;2.采购不开票且采购价格不含税
        has_prod_tax = product.sp_tax_rate and product.sp_tax_rate != '0';
        if((has_pur_invoice and has_prod_tax) or (not has_pur_invoice and not has_prod_tax)):
            return product_vals
        price = product_vals['value'].get('price_unit');
        #1.采购开票但采购价格不含税;
        if has_pur_invoice and not has_prod_tax:
            if product.pur_inv_gap and product.pur_inv_gap > 0: 
                    price = price + product.pur_inv_gap
            elif partner and partner.pur_invoice_rate and partner.pur_invoice_rate > 0:
                price = price*(1.0+float(partner.pur_invoice_rate)/100)
        #1.采购不开票但采购价格含税;
        if not has_pur_invoice and has_prod_tax:
            if product.pur_inv_gap and product.pur_inv_gap > 0: 
                    price = price - product.pur_inv_gap
            elif partner and partner.pur_invoice_rate and partner.pur_invoice_rate > 0:
                price = price*(1.0-float(partner.pur_invoice_rate)/100)             
        product_vals['value'].update({'price_unit': price})  
        return product_vals
    #Since we changed the purchase_order_line.onchange_product_id() parameters, 
    #added 'has_pur_invoice', so we need to change this method also, since it call onchange_product_id
    def onchange_product_uom(self, cr, uid, ids, pricelist_id, product_id, qty, uom_id,
            partner_id, date_order=False, fiscal_position_id=False, date_planned=False,
            name=False, price_unit=False, has_pur_invoice=False, context=None):
        """
        onchange handler of product_uom.
        """
        if not uom_id:
            return {'value': {'price_unit': price_unit or 0.0, 'name': name or '', 'product_uom' : uom_id or False}}
        return self.onchange_product_id(cr, uid, ids, pricelist_id, product_id, qty, uom_id,
            partner_id, date_order=date_order, fiscal_position_id=fiscal_position_id, date_planned=date_planned,
            name=name, price_unit=price_unit, has_pur_invoice = has_pur_invoice,context=context)    
        

#redefine the purchase PDF report to new rml
from openerp.addons.purchase.report.order import order
from openerp.report import report_sxw
class pur_order_printer(order):
    def __init__(self, cr, uid, name, context):
        super(order, self).__init__(cr, uid, name, context=context)
        self.localcontext.update({'get_main_contacter':self._get_main_contacter})
        self.localcontext.update({'repeatIn':self.repeatIn,
                                  'uom_digits':self.get_uom_digits})        
    #get the main contacer name/phone/mobile             
    def _get_main_contacter(self,partner):
        res_partner = self.pool.get('res.partner');
        contacter_id = res_partner.search(self.cr,self.uid,[('parent_id', '=', partner.id),('is_main_contact', '=', True)],limit=1)
        if len(contacter_id) == 0: return ""
        contacter = res_partner.browse(self.cr,self.uid,contacter_id[0])
        return contacter.name + '/' + (contacter.phone or '') + '/' + (contacter.mobile or '')
    #add the idx(1...n) to the repeatIn() iteration objects in PDF
    def repeatIn(self, lst, name,nodes_parent=False):
        ret_lst = super(pur_order_printer,self).repeatIn(lst, name,nodes_parent)
        i = 0
        for obj in ret_lst:
            i = i + 1
            obj.get(name).idx = i
        return ret_lst            
report_sxw.report_sxw('report.purchase.order.lijin', 'purchase.order', 'addons/lijin/report/purchase_order.rml', parser=pur_order_printer, header="external")
report_sxw.report_sxw('report.purchase.quotation.lijin','purchase.order','addons/lijin/report/purchase_order.rml',parser=pur_order_printer, header="external")            
        